<template>
  <div class="app-container">
    <div class="filter-container">
      <el-card>
        <el-form ref="searchform" :inline="true" :model="searchform" class="demo-form-inline" size="small">
          <el-form-item label="标题：">
            <el-input v-model="searchform.Keywords" clearable placeholder="秒杀商品标题" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <div class="list-btn-container">
        <el-button-group>
          <slot v-for="itemf in loadBtnFunc">
            <el-button v-if="itemf.FullName==='新增'" type="default" icon="el-icon-plus" size="small" @click="ShowEditOrViewDialog()">新增</el-button>
            <el-button v-if="itemf.FullName==='修改'" type="default" icon="el-icon-edit" size="small" @click="ShowEditOrViewDialog('edit')">修改</el-button>
            <el-button v-if="itemf.FullName=='禁用'" type="default" icon="el-icon-video-pause" size="small" @click="setEnable('0')">禁用</el-button>
            <el-button v-if="itemf.FullName=='启用'" type="default" icon="el-icon-video-play" size="small" @click="setEnable('1')">启用</el-button>
            <!-- <el-button v-if="itemf.FullName==='软删除'" type="default" icon="el-icon-delete" size="small" @click="deleteSoft('0')">软删除</el-button> -->
          </slot>
          <el-button type="default" icon="el-icon-refresh" size="small" @click="loadTableData()">刷新</el-button>
        </el-button-group>
      </div>
      <el-table
        ref="gridtable"
        v-loading="tableloading"
        :data="tableData"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        :default-sort="{prop: 'SortCode', order: 'descending'}"
        @select="handleSelectChange"
        @select-all="handleSelectAllChange"
        @sort-change="handleSortChange"
      >
        <el-table-column
          type="selection"
          width="30"
        />
        <el-table-column
          prop="Id"
          label="编号"
          sortable="custom"
          width="230"
          align="center"
        />
        <el-table-column
          prop="Title"
          label="标题"
          sortable="custom"
          width="230"
          align="center"
        />
        <!-- <el-table-column
          prop="GoodsDto.Id"
          label="关联商品编号"
          sortable="custom"
          width="180"
          align="center"
        /> -->
        <el-table-column
          prop="GoodsDto.Title"
          label="关联商品名称"
          sortable="custom"
          width="190"
          align="center"
        />
        <el-table-column
          prop="Discount"
          label="秒杀折扣"
          sortable="custom"
          width="190"
          align="center"
        />
        <el-table-column
          prop="Stock"
          label="库存"
          sortable="custom"
          width="190"
          align="center"
        />
        <el-table-column
          prop="StartTime"
          label="开始时间"
          sortable="custom"
          width="190"
          align="center"
        />
        <el-table-column
          prop="EndTime"
          label="结束时间"
          sortable="custom"
          width="190"
          align="center"
        />
        <!-- <el-table-column
          prop="Sort"
          label="排序"
          sortable="custom"
          width="190"
          align="center"
        /> -->
        <el-table-column
          label="可用"
          sortable="custom"
          width="90"
          prop="EnabledMark"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.EnabledMark === true ? 'success' : 'info'"
              disable-transitions
            >{{ scope.row.EnabledMark===true?'启用':'禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="ShowEditOrViewDialog('select',scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="pagination.currentPage"
          :page-sizes="[5,10,20,50,100, 200, 300, 400]"
          :page-size="pagination.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog ref="dialogEditForm" :title="editFormTitle+'秒杀商品'" :visible.sync="dialogEditFormVisible" width="900px">
      <el-form ref="editFrom" :model="editFrom" :rules="rules" class="demo-form-inline">
        <el-form-item label="商品" :label-width="formLabelWidth" prop="GoodsId">
          <el-select
            v-model="editFrom.GoodsId"
            style="width:400px"
            filterable
            placeholder="请选择商品"
            :disabled="IsDisabledUpdata"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀标题" :label-width="formLabelWidth" prop="Title">
          <el-input v-model="editFrom.Title" :disabled="IsDisabled" placeholder="请输入秒杀标题" autocomplete="off" clearable style="width:400px;" />
        </el-form-item>
        <el-form-item label="折扣" :label-width="formLabelWidth" prop="Discount">
          <el-input-number v-model="editFrom.Discount" :disabled="IsDisabled" :min="1" :max="100" placeholder="请输入折扣" autocomplete="off" clearable style="width:400px;" />
        </el-form-item>
        <el-form-item label="秒杀库存" :label-width="formLabelWidth" prop="Stock">
          <el-input v-model="editFrom.Stock" :disabled="IsDisabled" placeholder="请输入秒杀库存" autocomplete="off" clearable style="width:400px;" />
        </el-form-item>
        <el-form-item label="最多可购买数量" :label-width="formLabelWidth" prop="OrderAtMostCount">
          <el-input v-model="editFrom.OrderAtMostCount" :disabled="IsDisabled" :min="1" :max="99" placeholder="请输入最多可购买数量" autocomplete="off" clearable style="width:400px;" />
        </el-form-item>
        <el-form-item label="开始日期" :label-width="formLabelWidth" prop="StartTime">
          <el-date-picker
            v-model="editFrom.StartTime"
            type="datetime"
            style="width:400px;"
            placeholder="开始日期"
            :disabled="IsDisabled"
          />
        </el-form-item>
        <el-form-item label="结束日期" :label-width="formLabelWidth" prop="EndTime">
          <el-date-picker
            v-model="editFrom.EndTime"
            type="datetime"
            style="width:400px;"
            placeholder="结束日期"
            :disabled="IsDisabled"
          />
        </el-form-item>
        <!-- <el-form-item label="排序" :label-width="formLabelWidth" prop="Sort">
          <el-input-number v-model="editFrom.Sort" :min="1" :disabled="IsDisabled" placeholder="请输入排序序号" style="width:400px;" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button :disabled="IsDisabled" type="primary" @click="saveEditForm()">保 存</el-button>
      </div>
      </el-form></el-dialog>
  </div>
</template>
<script>

import { getPage, save, getDetail, delSoft, GetAllGoodsEnable, setEnable } from '@/api/shop/goodsseckillservice'
import defaultSettings from '@/settings'
import * as fecha from 'element-ui/lib/utils/date'
// import EleUploadImage from '@/components/upload/EleUploadImage'
export default {
  components: {
    // EleUploadImage
  },
  data() {
    return {
      activeName: 'first',
      IsDisabled: false,
      isClear: false,
      content: '',
      options: [],
      searchform: {
        Keywords: '',
        BrandId: '',
        CategoryId: '',
        Type: '',
        GoodsOnState: null,
        GoodsSortByEnum: null

      },

      selectRole: [],
      selectCategoryOptions: [],
      selectOrganize: [],
      GoodsImages: '',
      loadBtnFunc: [],
      tableData: [],
      IsDisabledUpdata: false,
      tableloading: true,
      pagination: {
        currentPage: 1,
        pagesize: 10,
        pageTotal: 0
      },
      sortableData: {
        // order: '',
        // sort: ''
      },
      dialogEditFormVisible: false,
      editFormTitle: '',
      editFrom: {
        Id: '',
        GoodsId: '',
        Title: '',
        Stock: 1,
        EnabledMark: true,
        CoverImageUrl: '',
        Sort: 99,
        Discount: 99,
        StartTime: null,
        EndTime: null,
        OrderAtMostCount: 1
      },
      rules: {
        GoodsId: [
          { required: true, message: '请选择商品', trigger: 'blur' }
        ],
        // Title: [
        //   { required: true, message: '请输入秒杀标题', trigger: 'blur' },
        //   { min: 2, max: 50, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        // ],
        Discount: [
          { required: true, message: '请输入折扣', trigger: 'blur' }
        ],
        StartTime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        EndTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        Stock: [
          { required: true, message: '请输入库存', trigger: 'blur' }
        ],
        OrderAtMostCount: [
          { required: true, message: '请输入最多可购买数量', trigger: 'blur' }
        ]
      },
      httpFileUploadUrl: defaultSettings.fileUploadUrl,
      dialogVisible: false,
      isShowDoctor: false,
      dialogImageUrl: '',
      filelist: [],
      dialogHeadIconVisible: false,
      dialogHeadIconImageUrl: '',
      formLabelWidth: '150px',
      currentId: '',
      currentSelected: []
    }
  },
  created() {
    this.pagination.currentPage = 1
    this.InitDictItem()
    this.loadTableData()
    this.loadBtnFunc = JSON.parse(localStorage.getItem('yueboncurrentfuns'))
  },
  methods: {
    InitDictItem() {
      GetAllGoodsEnable().then(res => {
        this.options = res.ResData.map(item => {
          return { value: `${item.Id}`, label: `${item.Title}` }
        })
      })
    },
    change(val) {
      console.log(val)
    },
    loadTableData: function() {
      this.tableloading = true
      var seachdata = {
        'CurrenetPageIndex': this.pagination.currentPage,
        'PageSize': this.pagination.pagesize,
        'Title': this.searchform.Keywords
      }
      getPage(seachdata).then(res => {
        this.tableData = res.ResData.Items
        this.pagination.pageTotal = res.ResData.TotalItems
        this.tableloading = false
      })
    },

    handleSearch: function() {
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    handleRemove(file, fileList) {
      console.log(file)
      this.editFrom.GoodsImages = file.url
      this.editFrom.GoodsFileRequests = this.editFrom.GoodsFileRequests.filter(s => s.Desc !== file.name)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    setEnable: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds,
          bltag: val
        }
        setEnable(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },
    ShowEditOrViewDialog: function(view, row) {
      if (row != null && row !== undefined) {
        this.currentId = row.Id
      } else {
        if (this.currentSelected !== '' && this.currentSelected.length > 0 && this.currentSelected[0].Id >= 0) {
          this.currentId = this.currentSelected[0].Id
        }
      }
      if (view !== undefined) {
        if (view === 'select') {
          this.editFormTitle = '查看'
          this.IsDisabled = true
          this.IsDisabledUpdata= true
          this.dialogEditFormVisible = true
          this.bindEditInfo()
        } else {
          if ((this.currentId.length < 0 || this.currentId.length === 0)) {
            this.$alert('请选择一条数据进行编辑/修改', '提示')
            return false
          }
          this.editFormTitle = '编辑'
          this.dialogEditFormVisible = true
          this.IsDisabled = false
          this.IsDisabledUpdata = true
          this.bindEditInfo()
        }
      } else {
        this.editFormTitle = '新增'
        this.IsDisabled = false
        this.IsDisabledUpdata = false
        this.currentId = ''
        this.dialogEditFormVisible = true
        this.$nextTick(function() {
          this.$refs['editFrom'].resetFields()
        })
      }
    },
    bindEditInfo: function() {
      getDetail(this.currentId).then(res => {
        this.editFrom.Title = res.ResData.Title
        this.editFrom.GoodsId = res.ResData.GoodsId
        this.editFrom.Discount = res.ResData.Discount
        this.editFrom.Stock = res.ResData.Stock
        this.editFrom.Sort = res.ResData.Sort
        this.editFrom.EndTime = res.ResData.EndTime
        this.editFrom.StartTime = res.ResData.StartTime
        this.editFrom.EnabledMark = res.ResData.EnabledMark
        this.editFrom.Id = res.ResData.Id
        this.editFrom.OrderAtMostCount = res.ResData.OrderAtMostCount
      })
    },
    /**
     * 新增/修改保存
     */
    saveEditForm() {
      console.log(this.editFrom.RoleId)
      this.$refs['editFrom'].validate((valid) => {
        if (valid) {
          const data = {
            GoodsId: this.editFrom.GoodsId,
            Title: this.editFrom.Title,
            Discount: this.editFrom.Discount,
            Stock: this.editFrom.Stock,
            Detail: this.content,
            Sort: this.editFrom.Sort,
            EnabledMark: this.editFrom.EnabledMark,
            DeleteMark: this.editFrom.DeleteMark,
            StartTime: this.editFrom.StartTime,
            EndTime: this.editFrom.EndTime,
            OrderAtMostCount: this.editFrom.OrderAtMostCount,
            'Id': this.currentId
          }

          var url = 'GoodsSeckill/create'
          if (this.currentId !== '') {
            url = 'GoodsSeckill/updateAsync'
          }
          save(data, url).then(res => {
            if (res.Success) {
              this.$message({
                message: '恭喜你，操作成功',
                type: 'success'
              })
              this.dialogEditFormVisible = false
              this.currentSelected = ''
              this.selectedOrganizeOptions = ''
              this.$nextTick(function() {
                this.$refs['editFrom'].resetFields()
              })
              this.loadTableData()
              this.InitDictItem()
            } else {
              this.$message({
                message: res.ErrMsg,
                type: 'error'
              })
            }
          })
        } else {
          this.$message.error('你有未填写的数据,请检查')
        }
      })
    },
    deleteSoft: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds,
          bltag: val
        }
        delSoft(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChange: function(column) {
      this.sortableData.sort = column.prop
      if (column.order === 'ascending') {
        this.sortableData.order = 'asc'
      } else {
        this.sortableData.order = 'desc'
      }
      this.loadTableData()
    },
    /**
     * 当用户手动勾选checkbox数据行事件
     */
    handleSelectChange: function(selection, row) {
      this.currentSelected = selection
    },
    /**
     * 当用户手动勾选全选checkbox事件
     */
    handleSelectAllChange: function(selection) {
      this.currentSelected = selection
    },
    /**
     * 选择每页显示数量
     */
    handleSizeChange(val) {
      this.pagination.pagesize = val
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    /**
     * 选择当页面
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTableData()
    },
    dateformatter(row, column, cellValue, index) {
      var date = row[column.property]
      return cellValue ? fecha.format(new Date(date), 'yyyy-MM-dd') : ''
    },
    uploadFileSuccess: function(response, file, fileList) {
      console.log(file)
      this.editFrom.FilePath = defaultSettings.fileUrl + response.ResData.FilePath
      this.editFrom.GoodsFileRequests.push({ UploadfileId: response.ResData.Id, Type: 1, Desc: response.ResData.FileName, IsCover: false })
    },
    handleResponse(response, file, fileList) {
      this.editFrom.CoverImageUrl = defaultSettings.fileUrl + response.ResData.FilePath
      this.editFrom.GoodsFileRequests = this.editFrom.GoodsFileRequests.filter(s => s.IsCover === false)
      this.editFrom.GoodsFileRequests.push({ UploadfileId: response.ResData.Id, Type: 1, Desc: response.ResData.FileName, IsCover: true })
      return file.url
    },
    onInput() {
      this.$forceUpdate()
    }
  }
}
</script>
